/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe*/
probe.filter("csv", function () {
	return function (input, separator) {
		separator = (separator || ',')[0];//default is ,

		var out = [],
			field = '',
			row = [],
			unquotedField = new RegExp("^([^\n\r\"" + separator + "]*)"),
			newline = /^(\r\n|\r|\n)/,
			i = 0,
			char,
			match,
			len = input.length;

		for (;;) {
			if (i === len) {
				if (row.length) {
					out.push(row);
				}

				break;
			}

			if (match = newline.exec(input.slice(i))) {
				row.push(field);
				field = '';
				out.push(row);
				row = [];
				i += match[0].length;
				continue;
			}

			char = input[i];

			if (char === separator) {
				row.push(field);
				field = '';
				i++;
				continue;
			}
			//parse field
			if (field.length) {
				throw new Error("unexpected value");
			}
			// quoted field
			if (char === '"') {
				i += 1;
				for (;;) {
					if (i >= len) {
						throw new Error("unterminated quoted field");
					}

					char = input[i];

					if (char === '"') {
						// "" = " in quoted field in csv standard
						if (input[i+1] === '"') {
							field += '"';
							i += 2;
							continue;
						} else {
							break;
						}
					}

					if (char === '\\') {
						field += input[i+1];
						i += 2;
					} else {
						field += char;

						i++;
					}
				}

				i += 1;
				continue;
			}

			//unquoted field
			if (match = unquotedField.exec(input.slice(i))) {
				field = match[1];
				i += match[0].length;
				continue;
			}

			throw new Error("unknown csv syntax");
		}

		return out;
	};
});